package com.woniuxy.micropermissionserver.adminmanage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.microcommonserver.bean.permission_hcz.Admin;
import com.woniuxy.microcommonserver.pageHelper.PageRequest;
import com.woniuxy.microcommonserver.pageHelper.TableResult;
import com.woniuxy.micropermissionserver.adminmanage.mapper.AdminMapper;
import com.woniuxy.micropermissionserver.adminmanage.service.IAdminService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class AdminServiceImpl implements IAdminService {


    @Resource
    private AdminMapper adminMapper;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void addAdmin(Admin admin, List<Integer> roleIds) {
        String pwd = new SimpleHash("MD5", admin.getPassword(), admin.getLoginName(), 1024).toString();
        admin.setPassword(pwd);
        admin.setDelFlag(false);
        admin.setForbidden(false);
        admin.setVersion(0);
        adminMapper.addAdmin(admin);
        if (!roleIds.isEmpty() && roleIds.size() > 0) {
            adminMapper.batchSaveAdminRole(admin.getId(), roleIds);
        }
    }

    @Override
    public Admin findById(Integer id) {
        return adminMapper.findById(id);
    }

    @Override
    public Admin login(String loginName) {
        return adminMapper.loginByName(loginName);
    }

    @Override
    public TableResult<Admin> findPage(PageRequest page, Admin admin) {
        PageInfo<Admin> pageInfo = PageHelper.startPage(page.getPageNum(), page.getLimit())
                .doSelectPageInfo(() -> adminMapper.findByParams(admin));
        TableResult<Admin> result = new TableResult<>();
        result.setTotal(pageInfo.getTotal());
        result.setRows(pageInfo.getList());
        return result;
    }

    @Override
    public List<Admin> findByParams(Admin admin) {
        return adminMapper.findByParams(admin);
    }
}
